package com.xiaozhen.security.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.common.core.domain.AjaxResult;
import com.xiaozhen.common.core.utils.ServletUtils;
import com.xiaozhen.common.core.utils.UserUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/8/17 16:24
 * @description:
 */
@Controller
public class BaseController {

    /**
     * 获取当前用户ID
     *
     * @return
     */
    public Long getCurrentUserId() {
        //return UserUtils.getCurrentUserId();
        return StpUtil.getLoginIdAsLong();
    }

    /**
     * mybatis-plus分页
     */
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    protected <T> Page<T> startPage() {
        Integer pageNum = ServletUtils.getParameterToInt(PAGE_NUM);
        if (pageNum == null) {
            pageNum = 1;
        }
        Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE);
        if (pageSize == null) {
            pageSize = 10;
        }
        Page<T> page = new Page<>(pageNum, pageSize);
        return page;
    }

    /**
     * 响应请求分页数据
     */
    protected AjaxResult getDataTable(Page<?> page) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("code", HttpStatus.OK.value());
        ajaxResult.put("msg", "查询成功");
        ajaxResult.put("rows", page.getRecords());
        ajaxResult.put("total", page.getTotal());
        return ajaxResult;
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected AjaxResult toAjax(boolean result) {
        return result ? success() : error();
    }

    /**
     * 返回成功
     */
    public AjaxResult success() {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error() {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message) {
        return AjaxResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message) {
        return AjaxResult.error(message);
    }
}
